//
//  VM6ShareCodeVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2024/12/9.
//  Copyright © 2024 Chun Hung Cheung. All rights reserved.
//

#import "CatShareCodeVController.h"

@interface CatShareCodeVController ()
@property(nonatomic,strong)UIScrollView *containerScrollview; // 底层的scrollview
@property(nonatomic,strong)UIView *containerView;// 添加到Scrollview 的view
@property(nonatomic,strong)UIView *codeContrainview;// 二维码容器
@property(nonatomic,strong)UIImageView *codeImageview;// 二维码
@property(nonatomic,strong)UIView *bottom_view;
@end

@implementation CatShareCodeVController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setup];
    
    self.containerScrollview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
    self.containerView.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
    self.codeContrainview.backgroundColor = [UIColor whiteColor];
    self.bottom_view.backgroundColor = [UIColor clearColor];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // 主用户创建分享token
    [SVProgressHUD showWithDuration:15];
    
    [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework create_share_token:self.bid] errorHint:^(id errorData) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Failed, please try later", nil)];
        NSLog(@"请求数据失败-->%@",errorData);
    } result:^(id data) {
        NSDictionary *dict = (NSDictionary*)data;
        NSInteger code = [[dict objectForKey:@"code"] integerValue];
        if (code == 0) {
            
            NSString *share_token = [dict objectForKey:@"share_token"];
            NSString *downAppLink =   [dict objectForKey:@"downAppLink"];
            NSString *invitation_code = [dict objectForKey:@"invitation_code"];
            NSString *coreStr = [NSString stringWithFormat:@"%@?share_token=%@&nickName=%@",downAppLink,share_token,[Tooles getuserToken]];
            
           // self.shareByPhone = [NSString stringWithFormat:@"%@?invitation_code=%@&qr_code_url=%@",shareUrl,invitation_code,messageStr];
            // http://www.eques.com.cn/app-download.php?&share_token=kkriSS9I3DsZA2bN836w9xALO6bls2JI&nickName=wxh123
          //  NSLog(@"分享给用户手机短信的 url== \n %@",self.shareByPhone);
            NSLog(@"拼接的二维码信息:coreStr == \n%@",coreStr);
            
            // 生成二维码
            self.codeContrainview.backgroundColor = [UIColor whiteColor];
            self.codeImageview.image  =  [self createQRImageWithString:coreStr QRSize:CGSizeMake(kScreenWidth*0.6, kScreenWidth*0.6)];
            if (invitation_code) {
                
                UIImage  *codeimage =  [self createQRImageWithString:coreStr QRSize:CGSizeMake(160, 160)];
            }
            
            [SVProgressHUD dismiss];
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"刷新成功",nil)];
            
        } else {
            
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"The device does not support sharing, generate qr code failed",nil)];
        }
    }];
        
       
    
}



- (void)setup
{
    
    
    self.containerScrollview.backgroundColor = [UIColor whiteColor];
    self.containerView.backgroundColor = [UIColor whiteColor];
   

    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     settingBtn.frame = CGRectMake(0, 0, 160, 20);
     settingBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18.0];
    [settingBtn setTitleColor:[HexChangeRGB colorWithHexString:@"#754c24"] forState:UIControlStateNormal];
    [settingBtn setTitle:NSLocalizedString(@"设备共享", nil) forState:UIControlStateNormal];
    self.navigationItem.titleView = settingBtn;
    
    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backbtn.frame = CGRectMake(0,0,80,40);
    backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
    backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
    [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#000000"] forState:UIControlStateNormal];
    [backbtn setImage: [UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];

}

- (void)selectLeftActionClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark: Scrollview视图
-(UIScrollView*)containerScrollview
{
    if (!_containerScrollview) {
         _containerScrollview = [[UIScrollView alloc]init];
         _containerScrollview.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *)) {
            _containerScrollview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
         _containerScrollview.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_containerScrollview];
        [_containerScrollview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
            make.width.equalTo(self.view.mas_width);
        }];
    }
    return _containerScrollview;
    
}

#pragma mark: Scrollview视图上的容纳视图
- (UIView*)containerView
{
    if (!_containerView) {
        _containerView = [[UIView alloc]init];
        [self.containerScrollview addSubview:_containerView];
        [_containerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.containerScrollview);
            make.width.equalTo(self.view.mas_width);
        }];
    }
    return _containerView;
}


- (UIView*)codeContrainview
{
    if (!_codeContrainview) {
       
         _codeContrainview = [[UIView alloc]init];
         _codeContrainview.layer.cornerRadius = 8;
         _codeContrainview.backgroundColor = [UIColor whiteColor];
         _codeContrainview.layer.masksToBounds = YES;
        [self.containerView addSubview:_codeContrainview];
        [_codeContrainview mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(kScreenWidth-28);
            make.height.mas_equalTo(420);
            make.centerX.equalTo(self.containerView.mas_centerX);
            make.top.equalTo(self.containerView.mas_top).offset(20);
        }];
        
         _codeImageview = [[UIImageView alloc]init];
        [_codeContrainview addSubview:_codeImageview];
        [_codeImageview mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(kScreenWidth*0.6);
            make.width.mas_equalTo(kScreenWidth*0.6);
            make.centerX.equalTo(_codeContrainview.mas_centerX);
            make.top.equalTo(_codeContrainview.mas_top).offset(50);
        }];
        
         UILabel *times_label = [[UILabel alloc]init];
         times_label.textAlignment = NSTextAlignmentCenter;
         times_label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
         times_label.textColor = [HexChangeRGB colorWithHexString:@"#3B86DD"];
        [_codeContrainview addSubview:times_label];
        [times_label mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_codeContrainview.mas_left);
            make.right.equalTo(_codeContrainview.mas_right);
            make.top.equalTo(_codeImageview.mas_bottom).offset(5);
        }];
        times_label.text = NSLocalizedString(@"十分钟内有效",nil);
        
    
       UIButton *_next_button = [[UIButton alloc]init];
        _next_button.layer.cornerRadius = 22;
        _next_button.layer.masksToBounds = YES;
       [_next_button addTarget:self action:@selector(savePhotohBtnClick) forControlEvents:UIControlEventTouchUpInside];
       [_codeContrainview addSubview:_next_button];
       [_next_button mas_makeConstraints:^(MASConstraintMaker *make) {
           make.width.mas_equalTo(260);
           make.height.mas_equalTo(44);
           make.bottom.equalTo(_codeContrainview.mas_bottom).offset(-40);
           make.centerX.equalTo(self.view.mas_centerX);
       }];
       _next_button.backgroundColor = [HexChangeRGB colorWithHexString:@"#FF7316"];
       _next_button.titleLabel.textColor = [UIColor whiteColor];
      [_next_button setImage:[UIImage imageNamed:@"code_download"] forState:UIControlStateNormal];
      [_next_button setTitle: NSLocalizedString(@"保存至手机相册", nil) forState:UIControlStateNormal];
      [_next_button SG_imagePositionStyle:SGImagePositionStyleDefault spacing:10];
        
        
    }

    return _codeContrainview;
}




#pragma mark - 创建二维码
- (UIImage*)createQRImageWithString:(NSString*)content QRSize:(CGSize)size
{
     NSData *stringData = [content dataUsingEncoding: NSUTF8StringEncoding];

    //生成
     CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 滤镜恢复默认设置
    [qrFilter setDefaults];
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
     CIImage *qrImage = qrFilter.outputImage;
    

    
    CGRect extent = CGRectIntegral(qrImage.extent);
    CGFloat scale = MIN(size.width/CGRectGetWidth(extent), size.width/CGRectGetHeight(extent));
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:qrImage fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];

}

- (UIView*)bottom_view
{
    if (!_bottom_view) {
         _bottom_view = [[UIView alloc]init];
         _bottom_view.layer.cornerRadius = 8;
         _bottom_view.backgroundColor = [UIColor whiteColor];
         _bottom_view.layer.masksToBounds = YES;
        [self.containerView addSubview:_bottom_view];
        [_bottom_view mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(kScreenWidth);
            make.height.mas_equalTo(300);
            make.centerX.equalTo(self.containerView.mas_centerX);
            make.top.equalTo(self.codeContrainview.mas_bottom).offset(40);
            make.bottom.equalTo(self.containerView.mas_bottom);
        }];
        
        /*
         "Three simple steps for easy sharing"="简单三步，轻松分享";
         "Save Album \n Local Album"="保存二维码 \n 至本地相册";
         "Download the Equations app \n and register an account"="下载叮咚APP \n 并注册账号";
         "Click on the top right corner “+” \n to scan and scan the code"="点击右上角“+” \n 使用扫一扫扫码";
         */
         UILabel *tips = [[UILabel alloc]init];
         tips.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
         tips.text = NSLocalizedString(@"简单三步，轻松分享", nil);
         tips.textAlignment = NSTextAlignmentCenter;
         tips.font = [UIFont fontWithName:@"PingFangSC-Medium" size:16];
        [_bottom_view addSubview:tips];
        [tips mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_bottom_view.mas_top);
            make.centerX.equalTo(_bottom_view.mas_centerX);
        }];
        

        UIView *leftline = [[UIView alloc]init];
         leftline.backgroundColor = [HexChangeRGB colorWithHexString:@"#e0e0e0"];
        [_bottom_view addSubview:leftline];
        [leftline mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(tips.mas_centerY);
            make.right.equalTo(tips.mas_left).offset(-10);
            make.width.mas_equalTo(45);
            make.height.mas_equalTo(1);
        }];
        
        UIView *rightline = [[UIView alloc]init];
         rightline.backgroundColor = [HexChangeRGB colorWithHexString:@"#e0e0e0"];
        [_bottom_view addSubview:rightline];
        [rightline mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(tips.mas_centerY);
            make.left.equalTo(tips.mas_right).offset(10);
            make.width.mas_equalTo(45);
            make.height.mas_equalTo(1);
        }];
       
        NSArray *array = @[@"share_code_download",@"share_code_arrow",@"share_code_follow",@"share_code_arrow",@"share_code_scan"];
        CGFloat margin = (kScreenWidth-40*5)/(array.count+1);
        for (int i = 0; i < array.count; i ++) {
            UIImageView *imageview = [[UIImageView alloc]init];
            [_bottom_view addSubview:imageview];
            [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(tips.mas_bottom).offset(25);
                make.left.equalTo(_bottom_view.mas_left).offset(margin + i*(margin+40));
                make.width.mas_equalTo(40);
                make.height.mas_equalTo(40);
            }];
            imageview.image = [UIImage imageNamed:array[i]];
        }
        
        NSArray *title_array = @[NSLocalizedString(@"保存二维码 \n 至本地相册",nil),NSLocalizedString(@"下载APP \n 并注册账号",nil),NSLocalizedString(@"点击右上角 “+” \n 扫一扫扫码",nil)];
        for (int i = 0; i < title_array.count; i ++) {
            UILabel *imageview_label = [[UILabel alloc]init];
            imageview_label.textColor = [HexChangeRGB colorWithHexString:@"#808080"];
            imageview_label.textAlignment = NSTextAlignmentCenter;
            imageview_label.numberOfLines = 0;
            imageview_label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
            [_bottom_view addSubview:imageview_label];
            [imageview_label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(tips.mas_bottom).offset(80);
                make.left.equalTo(_bottom_view.mas_left).offset(i*(kScreenWidth/3));
                make.width.mas_equalTo(kScreenWidth/3);
            }];
            imageview_label.text = title_array[i];
        }
        
    }
    
    return _bottom_view;
}


#pragma mark: view获得截图 生成图片
-(UIImage*)captureView:(UIView *)theView{
    CGRect rect = theView.frame;
    if ([theView isKindOfClass:[UIScrollView class]]) {
        rect.size = ((UIScrollView *)theView).contentSize;
    }
    UIGraphicsBeginImageContext(rect.size);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

#pragma mark:保存图片按钮点击
- (void)savePhotohBtnClick
{
    if (![Tooles albumAccess]) {
      
        UIAlertView *albumaccessAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"请打开手机相册权限", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"sure", nil), nil];
        albumaccessAlertView.tag = 701;
       [albumaccessAlertView show];
        
        return;
    }
 
    if ([self captureView:self.containerView]) {
        UIImageWriteToSavedPhotosAlbum([self captureView:self.containerView],self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
    }else{
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"The device does not support sharing, generate qr code failed",nil)];
    }
}





#pragma mark:保存图片到本地
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    if(error) {
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"保存失败",nil)];
    } else {
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"保存成功",nil)];
    }
}


@end
